package com.sto.stoapp.activity.scanner;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.TextView;

import com.sto.stoapp.activity.R;
import com.sto.stoapp.activity.StoBillFiterActivity;
import com.sto.stoapp.activity.StoLoginActivity;
import com.sto.stoapp.activity.administrator.system.AdminSystemSettingActivity;
import com.sto.stoapp.activity.sales.SalesProblemPieceSelectActivity;
import com.sto.stoapp.activity.sales.SalesServerPointSmsActivity;
import com.sto.stoapp.activity.sales.SalesTelphoneSmsActivity;
import com.sto.stoapp.activity.sales.SalesWdcpQueryActivity;
import com.sto.stoapp.activity.sales.StoSitePointSelectActivity;
import com.sto.stoapp.adapter.SoleMainAdapter;
import com.sto.stoapp.broadcast.HomeBroadAction;
import com.sto.stoapp.broadcast.LogoutBroad;
import com.sto.stoapp.db.StoFilePreference;
import com.sto.stoapp.entity.FunctionEntity;
import com.sto.stoapp.listener.OnBackClickListener;
import com.sto.stoapp.listener.StoOnItemClickListener;
import com.sto.stoapp.manager.AlarmClockManager;
import com.sto.stoapp.server.StoDownServer;
import com.sto.stoapp.service.TimingService;
import com.sto.stoapp.upload.UploadDataService;
import com.sto.stoapp.util.Helper;
import com.sto.stoapp.util.UnifiedStaticType;
import com.sto.stoapp.widget.BaseActivity;
import com.sto.stoapp.widget.BaseDialog;

import java.util.ArrayList;
import java.util.List;

import sto.android.app.StoPdaKeyEvent;

public class StoScanMainActivity extends BaseActivity {

    // 按键映射
    private final int[] MAPP_TO_KEY = {R.string.handover_scan,
            R.string.server_point_sms, R.string.received_piece,
            R.string.send_piece, R.string.arrived_piece,
            R.string.deliver_piece, R.string.problem_piece,
            R.string.keep_ware_piece, R.string.package_send_piece,
            R.string.vehicle_operation, R.string.h_received_piece};
    private GridView scanMainList;

    private SoleMainAdapter soleAdapter;

    // private Boolean checkTimeRet=false;
    private LogoutBroad logoutBroad;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sto_scan_main);
        this.setStoTitle(R.string.busniess_scan);
        this.register(HomeBroadAction.SCANNER_MAN_BROAD);
        initWidget();
        // 登入类型,用于后面业务判断是业务员或扫描员类型,管理员...
        // UnifiedStaticType.loginType = BaseMessage.SCANNER_VERSION;
        // UnSentDataManager.getInstance().setUnSent(
        // UploadDataManager.getInstance(this).getUnsendDataCount());
        initUnsentDataCount();
    }

    private void initWidget() {
        scanMainList = (GridView) findViewById(R.id.scan_main_list);
        soleAdapter = new SoleMainAdapter(this, getResourceList());
        scanMainList.setAdapter(soleAdapter);
        scanMainList.setOnItemClickListener(new StoOnItemClickListener(this) {

            @Override
            public void KcOnItemClickListener(AdapterView<?> parent, View view,
                                              int position, long id) {
                view.setSelected(true);
                TextView title = (TextView) view.findViewById(R.id.res_test);
                clickItemEvent(title.getText().toString());

            }
        });

    }

    private void clickItemEvent(String title) {
        // 网点-收件
        if (title.equals(getText(R.string.received_piece))) {
            // if(checkTimeSyn()){
            // Intent intent = new Intent(this, StoScanReceiveActivity.class);
            // intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            // startActivity(intent);

            // }
            checkTimeSyn(StoScanReceiveActivity.class, this, "");
        }
        // 网点-发件
        else if (title.equals(getText(R.string.send_piece))) {
            // if(checkTimeSyn()){
            // Intent intent = new Intent(this, StoScanSendPieceActivity.class);
            // intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            // startActivity(intent);
            // }
            checkTimeSyn(StoScanSendPieceActivity.class, this, "");
        }
        // 网点-到件
        else if (title.equals(getText(R.string.to_piece))) {
            // if(checkTimeSyn()){
            // Intent intent = new Intent(this, StoScanToPieceActivity.class);
            // intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            // startActivity(intent);
            // }
            checkTimeSyn(StoScanToPieceActivity.class, this, "");
        }
        // 网点-派件
        else if (title.equals(getText(R.string.assign_piece))) {
            // if(checkTimeSyn()){
            // Intent intent = new Intent(this,
            // StoScanAssignPieceActivity.class);
            // intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            // startActivity(intent);
            // }
            checkTimeSyn(StoScanAssignPieceActivity.class, this, "");
        }
        // 网点-有派无签
        else if (title.equals(getText(R.string.youpaiwuqian))) {
            Intent intent = new Intent(this, StoYouPaiWuQianQueryActivity.class);
            intent.putExtra("busiType", HomeBroadAction.SCANNER_MAN_BROAD);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }
        // 网点-问题件
        else if (title.equals(getText(R.string.problem_piece))) {
            // if(checkTimeSyn()){
            // Intent intent = new Intent(this,
            // SalesProblemPieceActivity.class);
            // intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            // startActivity(intent);
            // }
            checkTimeSyn(SalesProblemPieceSelectActivity.class, this,
                    HomeBroadAction.SCANNER_MAN_BROAD);
        }
        // 网点-留仓件
        else if (title.equals(getText(R.string.stay_warehourse_piece))) {
            // if(checkTimeSyn()){
            // Intent intent = new Intent(this,
            // StoScanStayWarehourseActivity.class);
            // intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            // startActivity(intent);
            // }
            checkTimeSyn(StoScanStayWarehourseActivity.class, this,
                    HomeBroadAction.SCANNER_MAN_BROAD);
        }
        // 网点-装袋&发件
        else if (title.equals(getText(R.string.package_send_piece))) {
            // if(checkTimeSyn()){
            // Intent intent = new Intent(this,
            // StoScanBagAndSendPieceActivity.class);
            // intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            // startActivity(intent);
            // }
            checkTimeSyn(StoScanBagAndSendPieceActivity.class, this,
                    HomeBroadAction.SCANNER_MAN_BROAD);
        }
        // 网点-车辆操作
        else if (title.equals(getText(R.string.vehicle_operation))) {
            Intent intent = new Intent(this, StoScanCarOperatActivity.class);
            intent.putExtra("busiType", HomeBroadAction.SCANNER_MAN_BROAD);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }
        // 网点-24小时扫描
        else if (title.equals(getText(R.string.h_received_piece))) {
            // if(checkTimeSyn()){
            // Intent intent = new Intent(this,
            // StoScanTwentyFourHoursActivity.class);
            // intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            // startActivity(intent);
            // }
            checkTimeSyn(StoScanTwentyFourHoursActivity.class, this, "");
        }
        // 网点-无点超派
        else if (title.equals(getText(R.string.super_limits_search))) {
            Intent intent = new Intent(this, SalesWdcpQueryActivity.class);
            intent.putExtra("busiType", HomeBroadAction.SCANNER_MAN_BROAD);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }
        // 网点-服务短信
        else if (title.equals(getText(R.string.server_point_sms))) {
            // if(checkTimeSyn()){
            // Intent intent = new Intent(this,
            // SalesServerPointSmsActivity.class);
            // intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            // startActivity(intent);
            // }
            checkTimeSyn(SalesServerPointSmsActivity.class, this,
                    HomeBroadAction.SCANNER_MAN_BROAD);
        }
        // 网点-删除错扫
        else if (title.equals(getText(R.string.del_error_code))) {
            Intent intent = new Intent(this,
                    StoDeleteWrongScanningActivity.class);
            intent.putExtra("busiType", HomeBroadAction.SCANNER_MAN_BROAD);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }
        // 网点-记录查询
        else if (title.equals(getText(R.string.record_search))) {
            Intent intent = new Intent(this, StoRecordscheckActivity.class);
            intent.putExtra("busiType", HomeBroadAction.SCANNER_MAN_BROAD);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }
        // 网点-记录上传
        else if (title.equals(getText(R.string.record_upload))) {
            Intent intent = new Intent(this, StoUploadMainActivity.class);
            intent.putExtra("busiType", HomeBroadAction.SCANNER_MAN_BROAD);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }
        // 网点-业务设置
        else if (title.equals(getText(R.string.business_settings))) {
            Intent intent = new Intent(this, StoBusinessSetupActivity.class);
            intent.putExtra("busiType", HomeBroadAction.SCANNER_MAN_BROAD);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }
        // 网点-电话短信
        else if (title.equals(getText(R.string.telphone_sms))) {
            Intent intent = new Intent(this, SalesTelphoneSmsActivity.class);
            intent.putExtra("busiType", HomeBroadAction.SCANNER_MAN_BROAD);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }
        // 网点-系统设置
        else if (title.equals(getText(R.string.system_settings))) {
            Intent intent = new Intent(this, AdminSystemSettingActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.putExtra(HomeBroadAction.BROAD_TYPE,
                    HomeBroadAction.SCANNER_MAN_BROAD);
            startActivity(intent);
        }
        // 网点-交接扫描
        else if (title.equals(getText(R.string.handover_scan))) {

            checkTimeSyn(StoScanHandoverActivity.class, this,
                    HomeBroadAction.SCANNER_MAN_BROAD);
        }
        else if(title.equals(getText(R.string.filter))){

            Intent intent = new Intent(this, StoBillFiterActivity.class);
            intent.putExtra("busiType", HomeBroadAction.SCANNER_MAN_BROAD);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);

        }
        // 网点-用户切换
        else {
            onBackPressed();
        }
    }

    private List<FunctionEntity> getResourceList() {
        int[] picIds;
        if (StoFilePreference.getInstance(this).get24Switch()) {
            picIds = new int[]{R.drawable.sign_in, R.drawable.received_piece,
                    R.drawable.send_piece, R.drawable.arrived_piece,
                    R.drawable.deliver_piece, R.drawable.problem_piece,
                    R.drawable.keep_ware_piece, R.drawable.package_send_piece,
                    R.drawable.h_received_piece, R.drawable.h_received_piece,
                    R.drawable.h_received_piece,
                    R.drawable.server_point_sms,
                    R.drawable.super_limits_search, R.drawable.del_error_code,
                    R.drawable.record_search, R.drawable.record_upload,
                    R.drawable.business_settings, R.drawable.kai_after_sales,
                    R.drawable.telphone_sms, R.drawable.bill_filter,
                    R.drawable.system_settings, R.drawable.logout};
        } else {
            picIds = new int[]{R.drawable.sign_in, R.drawable.received_piece,
                    R.drawable.send_piece, R.drawable.arrived_piece,
                    R.drawable.deliver_piece, R.drawable.problem_piece,
                    R.drawable.keep_ware_piece, R.drawable.package_send_piece,
                    R.drawable.h_received_piece, R.drawable.h_received_piece,
                    //	R.drawable.h_received_piece,
                    R.drawable.server_point_sms,
                    R.drawable.super_limits_search, R.drawable.del_error_code,
                    R.drawable.record_search, R.drawable.record_upload,
                    R.drawable.business_settings, R.drawable.kai_after_sales,
                    R.drawable.telphone_sms, R.drawable.bill_filter,
                    R.drawable.system_settings, R.drawable.logout};
        }
        List<String> resList = new ArrayList<String>();
        //resList.add(getText(R.string.handover_scan).toString());
        resList.add(getText(R.string.received_piece).toString());
        resList.add(getText(R.string.send_piece).toString());
        resList.add(getText(R.string.arrived_piece).toString());
        resList.add(getText(R.string.deliver_piece).toString());
        resList.add(getText(R.string.problem_piece).toString());
        resList.add(getText(R.string.keep_ware_piece).toString());
        resList.add(getText(R.string.package_send_piece).toString());
        //resList.add(getText(R.string.youpaiwuqian).toString());
        resList.add(getText(R.string.vehicle_operation).toString());
        if (StoFilePreference.getInstance(this).get24Switch())
            resList.add(getText(R.string.h_received_piece).toString());
        resList.add(getText(R.string.server_point_sms).toString());
        resList.add(getText(R.string.super_limits_search).toString());
        resList.add(getText(R.string.del_error_code).toString());
        resList.add(getText(R.string.record_search).toString());
        resList.add(getText(R.string.record_upload).toString());
        resList.add(getText(R.string.business_settings).toString());
        resList.add(getText(R.string.telphone_sms).toString());
        resList.add(getText(R.string.system_settings).toString());
        resList.add(getText(R.string.filter).toString());
        resList.add(getText(R.string.logout).toString());
        List<FunctionEntity> functionList = new ArrayList<FunctionEntity>();
        for (int i = 0; i < resList.size(); i++) {
            FunctionEntity entity = new FunctionEntity();
            entity.setTitle(resList.get(i));
            entity.setPicId(picIds[i]);
            functionList.add(entity);
        }
        return functionList;
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        // 退出
        if (intent.getStringExtra(AlarmClockManager.ALARM_CLOCK_TYPE) != null) {
            if ((Intent.FLAG_ACTIVITY_CLEAR_TOP & intent.getFlags()) != 0
                    && intent
                    .getStringExtra(AlarmClockManager.ALARM_CLOCK_TYPE)
                    .equals(HomeBroadAction.ALARM_LOGOUT)) {
                // StoFilePreference.getInstance(this).clearLoginInfo();
                // StoFilePreference.getInstance(this).clearOderAndTimeSynData();
                Intent logoutIntent = new Intent(this, StoLoginActivity.class);
                startActivity(logoutIntent);
                finish();
            }
        }
    }

    /**
     * 时间同步检测
     *
     * @param c
     * @param type
     */
    private void checkTimeSyn(final Class<?> c, final Context context,
                              final String type) {
        if (!(StoFilePreference.getInstance(StoScanMainActivity.this)
                .getsetTimeSynch())) {
            final BaseDialog dialog = new BaseDialog(this);
            dialog.setTitles(getString(R.string.synch_time_hint));
            dialog.show();
            dialog.setOnBackClickListener(new OnBackClickListener() {

                @Override
                public void onBackClickListener(boolean res) {
                    dialog.dismiss();
                    if (res) {
                        Intent intent = new Intent(context, c);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        intent.putExtra("busiType", type);
                        startActivity(intent);
                    }
                }
            });
        } else {
            Intent intent = new Intent(context, c);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.putExtra("busiType", type);
            this.startActivity(intent);
        }
    }

    /**
     * 小退 返回网点选择状态
     */
    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
//		if (AccessControlManager.getInstance(this).getJobSelect()) {
        if (keyCode == StoPdaKeyEvent.KEYCODE_DEL) {
            startActivity(new Intent(this, StoSitePointSelectActivity.class)
                    .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
            this.finish();
        }
//		}
        return super.onKeyUp(keyCode, event);
    }

    /**
     * 退回到登入界面
     */
    @Override
    public void onBackPressed() {
        /*
		 * new AlertDialog.Builder(this) .setTitle(R.string.prompt)
		 * .setMessage(R.string.change_user) .setPositiveButton(R.string.change,
		 * new DialogInterface.OnClickListener() {
		 * 
		 * @Override public void onClick(DialogInterface dialog, int which) { //
		 * 恢复时间同步和订单状态 //
		 * StoFilePreference.getInstance(StoScanMainActivity.this)
		 * .clearOderAndTimeSynData(); Intent intent = new Intent(
		 * StoScanMainActivity.this, StoLoginActivity.class);
		 * startActivity(intent); finish(); } })
		 * .setNegativeButton(R.string.cancel, new
		 * DialogInterface.OnClickListener() {
		 * 
		 * @Override public void onClick(DialogInterface dialog, int which) {
		 * dialog.dismiss(); } }).setCancelable(false).show();
		 */
        Helper.logoutAlert(this);
        // super.onBackPressed();
    }

    /**
     * 注册广播
     *
     * @param action 事件
     */
    public void register(String action) {
        IntentFilter filter = new IntentFilter(action);
        logoutBroad = new LogoutBroad();
        registerReceiver(logoutBroad, filter);
    }

    /**
     * 注销广播
     */
    private void unRegister() {
        if (logoutBroad != null) {
            unregisterReceiver(logoutBroad);
        }
    }

    @Override
    protected void onDestroy() {
        // 退出的时候关闭后台服务
        System.out.println("onDestroy Scan");
        if (soleAdapter != null) {
            soleAdapter = null;
        }
        if (scanMainList != null) {
            scanMainList = null;
        }
        unRegister();
        if (!UnifiedStaticType.NOT_CLOSE) {
            StoFilePreference.getInstance(StoScanMainActivity.this)
                    .clearOderAndTimeSynData();
            stopService(new Intent(this, StoDownServer.class));
            stopService(new Intent(this, UploadDataService.class));
            stopService(new Intent(this, TimingService.class));
        }
        UnifiedStaticType.NOT_CLOSE = false;
        super.onDestroy();
    }

//	/**
//	 * 按键映射 数字键0~9映射（0表示列表第十条数据）
//	 */
//	@Override
//	public boolean onKeyDown(int keyCode, KeyEvent event) {
//		if (keyCode >= KeyEvent.KEYCODE_0 && keyCode <= KeyEvent.KEYCODE_9) {
//			clickItemEvent(getString(MAPP_TO_KEY[keyCode - KeyEvent.KEYCODE_0]));
//		}
//		return super.onKeyDown(keyCode, event);
//	}

}
